package com.thinvent.recommend.manager.manager.impl;

import com.thinvent.recommend.entity.KbFileInfo;
import com.thinvent.recommend.manager.dto.Pager;
import com.thinvent.recommend.manager.manager.FileInfoManager;
import com.thinvent.recommend.mapper.KbFileInfoMapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Collections;
import java.util.List;

/**
 * 文件信息管理器实现
 */
@Component
public class FileInfoManagerImpl implements FileInfoManager {
    private static final Logger log = LoggerFactory.getLogger(FileInfoManagerImpl.class);

    @Resource
    private KbFileInfoMapper kbFileInfoMapper;

    /**
     * 全量分页查询
     */
    @Override
    public Pager<KbFileInfo> listActiveFiles(int pageNum, int pageSize) {
        return listActiveFiles(pageNum, pageSize, null, null);
    }

    /**
     * 按时间区间或全量分页查询
     */
    @Override
    public Pager<KbFileInfo> listActiveFiles(int pageNum,
                                             int pageSize,
                                             LocalDateTime startTime,
                                             LocalDateTime endTime) {
        try {
            int offset = (pageNum - 1) * pageSize;
            List<KbFileInfo> list;
            long total;

            if (startTime == null && endTime == null) {
                // 全量
                list  = kbFileInfoMapper.selectAllActive(offset, pageSize);
                total = kbFileInfoMapper.countAllActive();
            } else {
                // 按时间区间查询（startTime 或 endTime 可为 null）
                list  = kbFileInfoMapper.selectActiveByTime(offset, pageSize, startTime, endTime);
                total = kbFileInfoMapper.countActiveByTime(startTime, endTime);
            }

            return new Pager<>(pageNum, pageSize, total, list);
        } catch (Exception e) {
            log.error("查询活动文件分页失败 pageNum={}, pageSize={}, startTime={}, endTime={}",
                    pageNum, pageSize, startTime, endTime, e);
            // 出错时返回空 Pager，不抛异常
            return new Pager<>(pageNum, pageSize, 0, Collections.emptyList());
        }
    }

    /**
     * 根据业务文件 ID 查询单条记录
     */
    @Override
    public KbFileInfo getFileInfoById(String fileId) {
        try {
            return kbFileInfoMapper.selectByPrimaryKey(fileId);
        } catch (Exception e) {
            log.error("根据 fileId={} 查询文档信息失败", fileId, e);
            return null;
        }
    }
}
